import { memo, useEffect, useRef } from 'react'
import { Navigate, useRoutes } from 'react-router-dom'
import { useMainStore } from '@/store/main'
import { mapRouters, addRouter } from './createRouter'
import 'nprogress/nprogress.css'
import type { IRouteObject } from './createRouter'

import Login from '@/layout/Login/Login' // 登录页
import Main from '@/layout/Main/Main' // 主区域容器
import Home from '@/views/Home/Home'
import NotFound from '@/layout/NotFound/NotFound' // 404页面

export const routes: IRouteObject[] = [
	{
		path: '/',
		element: <Navigate to="/login" />
	},
	{
		name: 'login',
		path: '/login',
		meta: { title: '登录' },
		element: <Login />
	},
	{
		name: 'main',
		// path: '/main',
		element: <Main />,
		children: [
			{
				name: 'home',
				path: '/home',
				meta: { title: '首页' },
				element: <Home />
			},
			{
				path: '*',
				element: <NotFound />
			}
		]
	},
	{
		path: '*',
		element: <NotFound />
	}
]

export const RouteList = memo(() => {
	const { userMenus, loadLocalStorage } = useMainStore()
	const isInitRef = useRef(false)

	useEffect(() => {
		loadLocalStorage()
	}, [])

	if (userMenus.length && !isInitRef.current) {
		const userAuthRouters = mapRouters(userMenus)
		addRouter('main', userAuthRouters)
		isInitRef.current = true
	}

	return useRoutes(routes)
})
